package cn.xiaobai.contorller;

import cn.xiaobai.domain.Message;
import cn.xiaobai.service.AuthorServer;
import cn.xiaobai.test;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.stage.Stage;
import javafx.stage.Window;

import java.io.IOException;


public class LoginController {
    @FXML
    private TextField username;

    @FXML
    private PasswordField password;

    @FXML
    private Button login_bt;

    private AuthorServer authorServer;

    public LoginController() {
        authorServer = new AuthorServer();
        Message message = authorServer.checkConn();
        Alert alert = new Alert(Alert.AlertType.NONE, message.getMsg());
        if (!message.isState()) {
            alert.setAlertType(Alert.AlertType.ERROR);
            alert.showAndWait()
                    .filter(type -> type == ButtonType.OK)
                    .ifPresent(e -> System.exit(0));
        }
    }

    @FXML
    protected void login_click() {
        String user = username.getText().trim();
        String pass = password.getText().trim();
        Message login = authorServer.login(user, pass);
        Alert alert = new Alert(Alert.AlertType.INFORMATION, login.getMsg());
        if (login.isState()) {
            alert.showAndWait()
                    .filter(bt -> bt == ButtonType.OK);

            Stage stage = (Stage) login_bt.getScene().getWindow();
            stage.close();
            try {
                // 窗体跳转测试
                new test().start();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            alert.setAlertType(Alert.AlertType.ERROR);
            alert.showAndWait()
                    .filter(bt -> bt == ButtonType.OK);
        }

    }

    @FXML
    protected void regis_click() {
        String user = username.getText().trim();
        String pass = password.getText().trim();
        Message regis = authorServer.regis(user, pass);
        Alert alert = new Alert(Alert.AlertType.INFORMATION, regis.getMsg());
        if (regis.isState()) {
            alert.showAndWait()
                    .filter(bt -> bt == ButtonType.OK);
        } else {
            alert.setAlertType(Alert.AlertType.ERROR);
            alert.showAndWait()
                    .filter(bt -> bt == ButtonType.OK);
        }

    }
}